//
//  WordCheckinView.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/5.
//

#import "WordCheckinView.h"

@interface WordCheckinView()

@property(nonatomic,strong)UIImageView *headImageView;
@property(nonatomic,strong)UILabel *nameLabel;
@property(nonatomic,strong)UILabel *dayLabel;
@property(nonatomic,strong)UILabel *totalDayLabel;
@property(nonatomic,strong)UIImageView *bgImageView;
@property(nonatomic,strong)UILabel *scoreLabel;
@property(nonatomic,strong)UILabel *shareScoreLabel;
@property(nonatomic,assign)CGFloat bg_max_w;
@property(nonatomic,assign)CGFloat bg_max_h;

@end

@implementation WordCheckinView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self.currentAvailableWidth = frame.size.width;
        self.currentAvailableHeight = frame.size.height;
        [self createUI];
    }
    return self;
}

-(void)createUI{
    
    __weak typeof(self)weakSelf = self;
    
    self.backgroundColor = UIColorHex_(0x000000,0.88);
    UITapGestureRecognizer *hiddenTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenTap:)];
    [self addGestureRecognizer:hiddenTap];
    
    CGFloat w335 = [DeviceUtils getAdaptedWidthForDesignWidth:335 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w456 = [DeviceUtils getAdaptedWidthForDesignWidth:456 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat h170 = [DeviceUtils getAdaptedHeightForDesignHeight:170 andCurrentAvailableHeight:self.currentAvailableHeight];
    CGFloat h80 = [DeviceUtils getAdaptedHeightForDesignHeight:80 andCurrentAvailableHeight:self.currentAvailableHeight];
    CGFloat h40 = [DeviceUtils getAdaptedHeightForDesignHeight:40 andCurrentAvailableHeight:self.currentAvailableHeight];
    CGFloat w48 = [DeviceUtils getAdaptedWidthForDesignWidth:48 andCurrentAvailableWidth:self.currentAvailableWidth];
    self.bg_max_w = w335;
    self.bg_max_h = w456;
    
    self.bgImageView = [[UIImageView alloc]init];
    self.bgImageView.backgroundColor = [UIColor clearColor];
    self.bgImageView.image = [UIImage imageNamed:@"word_checkin_bg"];
    [self addSubview:self.bgImageView];
    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        if(isIPAD){
            CGFloat max_h = (weakSelf.currentAvailableHeight-h170-h80-w48-24);
            if(w456 > max_h){
                CGFloat max_w = max_h*335/456;
                if(max_w > (weakSelf.currentAvailableWidth-40)){
                    max_w = weakSelf.currentAvailableWidth-40;
                }
                make.height.mas_equalTo(max_h);
                make.width.mas_equalTo(max_w);
                weakSelf.bg_max_w = max_w;
                weakSelf.bg_max_h = max_h;
            }else{
                make.width.mas_equalTo(w335);
                make.height.mas_equalTo(w456);
            }
        }else{
            make.width.mas_equalTo(w335);
            make.height.mas_equalTo(w456);
        }
        make.top.mas_equalTo(h170);
        make.centerX.mas_equalTo(weakSelf);
    }];
    
    CGFloat proportion = 1.0; // 根据最大高度计算比例
    if(isIPAD){
        proportion = self.bg_max_w/w335; // 根据最大高度计算比例
    }

    CGFloat w30 = [DeviceUtils getAdaptedWidthForDesignWidth:30 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w60 = [DeviceUtils getAdaptedWidthForDesignWidth:60 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w38 = [DeviceUtils getAdaptedWidthForDesignWidth:38 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w34 = [DeviceUtils getAdaptedWidthForDesignWidth:34 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w28 = [DeviceUtils getAdaptedWidthForDesignWidth:28 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w16 = [DeviceUtils getAdaptedWidthForDesignWidth:16 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w4 = [DeviceUtils getAdaptedWidthForDesignWidth:4 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w21 = [DeviceUtils getAdaptedWidthForDesignWidth:21 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w33 = [DeviceUtils getAdaptedWidthForDesignWidth:33 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w123 = [DeviceUtils getAdaptedWidthForDesignWidth:123 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w66 = [DeviceUtils getAdaptedWidthForDesignWidth:66 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w39 = [DeviceUtils getAdaptedWidthForDesignWidth:39 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w46 = [DeviceUtils getAdaptedWidthForDesignWidth:46 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w8 = [DeviceUtils getAdaptedWidthForDesignWidth:8 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w18 = [DeviceUtils getAdaptedWidthForDesignWidth:18 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w9 = [DeviceUtils getAdaptedWidthForDesignWidth:9 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w11 = [DeviceUtils getAdaptedWidthForDesignWidth:11 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w5 = [DeviceUtils getAdaptedWidthForDesignWidth:5 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w236 = [DeviceUtils getAdaptedWidthForDesignWidth:236 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w307 = [DeviceUtils getAdaptedWidthForDesignWidth:307 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w20 = [DeviceUtils getAdaptedWidthForDesignWidth:20 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w52 = [DeviceUtils getAdaptedWidthForDesignWidth:52 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w53 = [DeviceUtils getAdaptedWidthForDesignWidth:53 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w27 = [DeviceUtils getAdaptedWidthForDesignWidth:27 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w54 = [DeviceUtils getAdaptedWidthForDesignWidth:54 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w24 = [DeviceUtils getAdaptedWidthForDesignWidth:24 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w6 = [DeviceUtils getAdaptedWidthForDesignWidth:6 andCurrentAvailableWidth:self.currentAvailableWidth];
    self.headImageView = [[UIImageView alloc]init];
    self.headImageView.layer.cornerRadius = w30* proportion;
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.headImageView.layer.borderWidth = 2.0;
    NSString *avatar = [[NSUserDefaults standardUserDefaults]objectForKey:@"avatar"];
    if(avatar){
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@"mine_head_default"]];
    }else{
        self.headImageView.image = [UIImage imageNamed:@"mine_head_default"];
    }
    [self.bgImageView addSubview:self.headImageView];
    [self.headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(w60* proportion);
        make.left.mas_equalTo(w38* proportion);
        make.top.mas_equalTo(w30* proportion);
    }];
    self.nameLabel = [[UILabel alloc]init];
    self.nameLabel.font = JPUIFontPingFangSCMedium(20);
    self.nameLabel.textColor = [UIColor whiteColor];
    NSString *nickname = [[NSUserDefaults standardUserDefaults]objectForKey:@"nickname"];
    if(nickname){
        self.nameLabel.text = nickname;
    }else{
        NSString *phone = [[NSUserDefaults standardUserDefaults]objectForKey:@"phone"];
        if(phone){
            self.nameLabel.text = [self hideMiddleDigits:phone];
        }else{
            self.nameLabel.text = @"日语岛民";
        }
    }
    [self.bgImageView addSubview:self.nameLabel];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(w34* proportion);
        make.left.mas_equalTo(weakSelf.headImageView.mas_right).offset(10);
        make.height.mas_equalTo(w28* proportion);
        make.right.mas_equalTo(-w16* proportion);
    }];
    UILabel *inviteLabel = [[UILabel alloc]init];
    inviteLabel.font = JPUIFontPingFangSCRegular(15);
    inviteLabel.textColor = [UIColor whiteColor];
    inviteLabel.text = @"邀请你参加单词打卡挑战～";
    [self.bgImageView addSubview:inviteLabel];
    [inviteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.nameLabel);
        make.top.mas_equalTo(weakSelf.nameLabel.mas_bottom).offset(w4* proportion);
        make.height.mas_equalTo(w21* proportion);
    }];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(w33* proportion,w123* proportion,self.bg_max_w-w33* proportion,w66* proportion)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.bgImageView addSubview:bgView];
    [bgView addRoundedCorners:UIRectCornerTopLeft|UIRectCornerBottomLeft withRadii:CGSizeMake(10,10)];
    
    CGFloat d_mid = (bgView.width-w39* proportion*7)/8.0;
    NSArray *dayArr = [self getDatesAndWeekdays];
    for(NSInteger i = 0;i < dayArr.count;i++){
        NSArray *darr = dayArr[i];
        UIImageView *dayBgImageView = [[UIImageView alloc]init];
        dayBgImageView.backgroundColor = [UIColor whiteColor];
        if(i == 3){
            dayBgImageView.image = [UIImage imageNamed:@"word_checkin_today"];
        }
        [bgView addSubview:dayBgImageView];
        [dayBgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(d_mid+i*(w39* proportion+d_mid));
            make.height.mas_equalTo(w46* proportion);
            make.width.mas_equalTo(w39* proportion);
            make.centerY.mas_equalTo(bgView);
        }];
        UILabel *dayLabel = [[UILabel alloc]init];
        dayLabel.textAlignment = NSTextAlignmentCenter;
        if(i == 3){
            dayLabel.font = JPUIFontPingFangBold(15);
            dayLabel.textColor = [UIColor whiteColor];
            dayLabel.text = @"今";
        }else{
            dayLabel.font = JPUIFontInterSemiBold(15);
            dayLabel.textColor = KFontBlackColor;
            dayLabel.text = darr[0];
        }
        [dayBgImageView addSubview:dayLabel];
        [dayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            if(i == 3){
                make.height.mas_equalTo(w21* proportion);
            }else{
                make.height.mas_equalTo(w18* proportion);
            }
            make.top.mas_equalTo(w6* proportion);
            make.left.right.mas_equalTo(@0);
        }];
        if(i == 3){
            UIImageView *tickImageView = [[UIImageView alloc]init];
            tickImageView.image = [UIImage imageNamed:@"summary_checkin_tick"];
            [dayBgImageView addSubview:tickImageView];
            [tickImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.mas_equalTo(-w9* proportion);
                make.width.mas_equalTo(w11* proportion);
                make.height.mas_equalTo(w8* proportion);
                make.centerX.mas_equalTo(dayBgImageView);
            }];
        }else{
            UILabel *weekLabel = [[UILabel alloc]init];
            weekLabel.font = JPUIFontPingFangSCRegular(8);
            weekLabel.textColor = KFontGrayColor;
            weekLabel.textAlignment = NSTextAlignmentCenter;
            weekLabel.text = darr[1];
            [dayBgImageView addSubview:weekLabel];
            [weekLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(@0);
                make.top.mas_equalTo(dayLabel.mas_bottom).offset(w5* proportion);
                make.height.mas_equalTo(w11* proportion);
            }];
        }
    }
    
    NSArray *checkinArr = @[@"已连续打卡",@"已累计打卡"];
    for (NSInteger i = 0; i < checkinArr.count; i++) {
        UILabel *checkinTipLabel = [[UILabel alloc]init];
        checkinTipLabel.font = JPUIFontPingFangSCRegular(14);
        checkinTipLabel.textColor = [UIColor whiteColor];
        checkinTipLabel.text = checkinArr[i];
        [self.bgImageView addSubview:checkinTipLabel];
        [checkinTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(w38* proportion);
            make.height.mas_equalTo(@20);
            if(i == 0){
                make.top.mas_equalTo(w236* proportion);
            }else{
                make.top.mas_equalTo(w307* proportion);
            }
            make.width.mas_equalTo(@80);
        }];
        UILabel *checkDayLabel = [[UILabel alloc]init];
        checkDayLabel.textAlignment = NSTextAlignmentRight;
        [self.bgImageView addSubview:checkDayLabel];
        [checkDayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-w16* proportion);
            make.left.mas_equalTo(checkinTipLabel.mas_right);
            make.height.mas_equalTo(@39);
            make.centerY.mas_equalTo(checkinTipLabel);
        }];
        if(i == 0){
            self.dayLabel = checkDayLabel;
        }else{
            self.totalDayLabel = checkDayLabel;
        }
    }
    
    UIView *codeBgView = [[UIView alloc]init];
    codeBgView.backgroundColor = [UIColor whiteColor];
    codeBgView.layer.cornerRadius = 6;
    codeBgView.layer.masksToBounds = YES;
    codeBgView.layer.borderWidth = 2;
    codeBgView.layer.borderColor = KFontBlackColor.CGColor;
    [self.bgImageView addSubview:codeBgView];
    [codeBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(w60* proportion);
        make.bottom.mas_equalTo(-w20* proportion);
        make.left.mas_equalTo(w30* proportion);
    }];
    UIImageView *codeImageView = [[UIImageView alloc]init];
    UIImage *codeImage =  [self createNonInterpolatedUIImageFormCIImage:[self createhnfgjQRcodedjgkgkWithUrlstring:SHARELINK] withSize:w52* proportion];
    if(codeImage){
        codeImageView.image = codeImage;
    }
    [codeBgView addSubview:codeImageView];
    [codeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(w52* proportion);
        make.centerX.mas_equalTo(codeBgView);
        make.centerY.mas_equalTo(codeBgView);
    }];
    UILabel *codeTipLabel = [[UILabel alloc]init];
    codeTipLabel.font = JPUIFontPingFangSCRegular(14);
    codeTipLabel.textColor = KFontGrayColor;
    codeTipLabel.text = @"长按识别二维码";
    [self.bgImageView addSubview:codeTipLabel];
    [codeTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-w53* proportion);
        make.height.mas_equalTo(w20* proportion);
        make.right.mas_equalTo(-w16* proportion);
        make.left.mas_equalTo(codeImageView.mas_right).offset(w20* proportion);
    }];
    UILabel *codeTipLabel2 = [[UILabel alloc]init];
    codeTipLabel2.font = JPUIFontPingFangSCMedium(14);
    codeTipLabel2.textColor = KFontBlackColor;
    codeTipLabel2.text = @"跟我一起开启日语学习吧～";
    [self.bgImageView addSubview:codeTipLabel2];
    [codeTipLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-w27* proportion);
        make.height.mas_equalTo(w20* proportion);
        make.right.mas_equalTo(-w16* proportion);
        make.left.mas_equalTo(codeImageView.mas_right).offset(w20* proportion);
    }];
    
    NSArray *arr = @[@"打卡成功已获得",@"分享成功可再获得"];
    for(NSInteger i = 0;i < arr.count;i++){
        UILabel *tipLabel = [[UILabel alloc]init];
        if(self.bg_max_w < 335){
            tipLabel.font = JPUIFontPingFangSCMedium(15);
        }else{
            tipLabel.font = JPUIFontPingFangSCMedium(17);
        }
        tipLabel.textColor = [UIColor whiteColor];
        if(i == 1){
            tipLabel.textAlignment = NSTextAlignmentRight;
        }
        tipLabel.text = arr[i];
        [self addSubview:tipLabel];
        CGFloat tip_w = [self getStringWidthWithText:tipLabel.text font:tipLabel.font viewHeight:24];
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            if(i == 0){
                make.left.mas_equalTo(weakSelf.bgImageView.mas_left).offset(20);
            }else{
                make.right.mas_equalTo(weakSelf.bgImageView.mas_right).offset(-20);
            }
            make.top.mas_equalTo(h80);
            make.height.mas_equalTo(@24);
            make.width.mas_equalTo(tip_w);
        }];
        UIImageView *pointImageView = [[UIImageView alloc]init];
        pointImageView.image = [UIImage imageNamed:@"mine_coin_checkin"];
        [self addSubview:pointImageView];
        [pointImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(@16);
            make.top.mas_equalTo(tipLabel.mas_bottom).offset(9);
            make.left.mas_equalTo(tipLabel.mas_left);
        }];
        UILabel *coinLabel = [[UILabel alloc]init];
        coinLabel.font = JPUIFontInterMedium(16);
        coinLabel.textColor = [UIColor whiteColor];
        [self addSubview:coinLabel];
        [coinLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(pointImageView.mas_right).offset(2);
            make.height.mas_equalTo(@19);
            make.centerY.mas_equalTo(pointImageView);
        }];
        if(i == 0){
            self.scoreLabel = coinLabel;
        }else{
            self.shareScoreLabel = coinLabel;
        }
    }
    
    NSArray *titleArr = @[@"微信好友",@"朋友圈",@"保存图片"];
    NSArray *imageArr = @[@"word_checkin_wechat",@"word_checkin_wechat_cycle",@"word_checkin_download"];
    CGFloat redix = (self.currentAvailableWidth-w48* proportion*3-w54* proportion*2)/2.0;
    for(NSInteger i = 0;i < titleArr.count;i++){
        UIButton *btn = [[UIButton alloc]init];
        btn.backgroundColor = UIColorHex_(0xffffff,0.2);
        btn.layer.cornerRadius =w24* proportion;
        btn.layer.masksToBounds = YES;
        [btn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        btn.tag = 100+i;
        [btn addTarget:self action:@selector(shareClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(w48* proportion);
            make.left.mas_equalTo(w54* proportion+i*(w48* proportion+redix));
            make.top.mas_equalTo(weakSelf.bgImageView.mas_bottom).offset(h40);
        }];
        UILabel *shareLabel = [[UILabel alloc]init];
        shareLabel.font = JPUIFontPingFangSCRegular(13);
        shareLabel.textColor = UIColorHex_(0xffffff,0.5);
        shareLabel.textAlignment = NSTextAlignmentCenter;
        shareLabel.userInteractionEnabled = YES;
        shareLabel.text = titleArr[i];
        [self addSubview:shareLabel];
        [shareLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(@18);
            make.top.mas_equalTo(btn.mas_bottom).offset(6);
            make.centerX.mas_equalTo(btn);
            make.width.mas_equalTo(@52);
        }];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf shareClickWithIndex:i];
        }];
        [shareLabel addGestureRecognizer:tap];
    }
    
   
}

-(void)refreshWidth{
    [self removeAllSubviews];
    [self createUI];
    self.scoreLabel.text = [NSString stringWithFormat:@"+%@",_checkinModel.dayLearnWord];
    self.shareScoreLabel.text = [NSString stringWithFormat:@"+%@",_checkinModel.shareTest];
    self.dayLabel.attributedText = [self changeDayStr:_checkinModel.seriesCount];
    self.totalDayLabel.attributedText = [self changeDayStr:_checkinModel.sum];
}

-(void)setCheckinModel:(CheckinModel *)checkinModel{
    _checkinModel = checkinModel;
    self.scoreLabel.text = [NSString stringWithFormat:@"+%@",checkinModel.dayLearnWord];
    self.shareScoreLabel.text = [NSString stringWithFormat:@"+%@",checkinModel.shareTest];
    self.dayLabel.attributedText = [self changeDayStr:checkinModel.seriesCount];
    self.totalDayLabel.attributedText = [self changeDayStr:checkinModel.sum];
}

#pragma mark - 隐藏点击
- (void)hiddenTap:(UITapGestureRecognizer *)gesture {
    CGPoint touchPoint = [gesture locationInView:self];
    // 判断点击位置是否在UIImageView内
    if (!CGRectContainsPoint(self.bgImageView.frame,touchPoint)) {
        // 点击位置不在UIImageView内，执行相应操作
        [self removeFromSuperview];
    }
}


-(NSMutableAttributedString*)changeDayStr:(NSString*)str{
    NSMutableAttributedString *pStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@ 天",str]];
    [pStr addAttribute:NSFontAttributeName value:JPUIFontInterMedium(32) range:NSMakeRange(0,str.length)];
    [pStr addAttribute:NSFontAttributeName value:JPUIFontPingFangSCRegular(13) range:NSMakeRange(str.length,pStr.length-str.length)];
    [pStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0,pStr.length)];
    return pStr;
}

#pragma mark - 分享点击
-(void)shareClick:(UIButton*)btn{
    NSInteger index = btn.tag-100;
    [self shareClickWithIndex:index];
}

-(void)shareClickWithIndex:(NSInteger)index{
    if(index == 0||index == 1){
        self.bgImageView.backgroundColor = UIColorHex_(0x000000,0.88);
        UIImage *lastImage = [self captureScreenForView:self.bgImageView];
        self.bgImageView.backgroundColor = [UIColor clearColor];
        if(_shareBlock){
            _shareBlock(index,lastImage);
        }
    }else{
        //保存图片
        __weak typeof(self)self_weak_ = self;
        [self isCanVisitPhotoLibrary:^(BOOL iscan) {
            if (iscan == YES) {
                [self_weak_ saveConfig];
            }else{
                [JPProgressHUD showMsg:@"未开启相册权限，请到设置中开启"];
            }
        }];
    }
}

#pragma mark - 保存截图
-(void)saveConfig{
    self.bgImageView.backgroundColor = UIColorHex_(0x000000,0.88);
    UIImage *lastImage = [self captureScreenForView:self.bgImageView];
    if(lastImage){
        UIImageWriteToSavedPhotosAlbum(lastImage,self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);
    }
}

#pragma mark - 图片保存状态
-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    self.bgImageView.backgroundColor = [UIColor clearColor];
    if (error == nil) {
        [JPProgressHUD showMsg:@"保存成功"];
    }else{
        [JPProgressHUD showMsg:@"保存失败"];
    }
}

#pragma mark - 获取底部截屏图片
- (UIImage *)captureScreenForView:(UIView *)currentView{
    if (CGRectIsEmpty(currentView.bounds)) {
        // 当前视图的尺寸为零，无法进行截图
        return nil;
    }
    // 开启一个绘图的上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(currentView.size.width, currentView.size.height), NO,0.0);
    // 作用于CALayer层的方法。将view的layer渲染到当前的绘制的上下文中。
    [currentView drawViewHierarchyInRect:CGRectMake(0, 0, currentView.frame.size.width, currentView.frame.size.height) afterScreenUpdates:YES];
    // 获取图片
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束绘图上下文
    UIGraphicsEndImageContext();
    
    return  viewImage;
}


#pragma mark - 手机号隐藏
-(NSString*)hideMiddleDigits:(NSString*)phoneNumber{
     NSString *maskedNumber = phoneNumber;
     if (phoneNumber.length == 13||phoneNumber.length == 11) {
         // 中国手机号码 86+11位
         // 台湾手机号码 886 +10 位
         // 香港、澳门手机号码 852+8位 853+8位
         // 日本手机号码 81+11位
         NSRange range = NSMakeRange(5,4);
         maskedNumber = [phoneNumber stringByReplacingCharactersInRange:range withString:@"****"];
     }else if (phoneNumber.length == 12) {
         // 香港手机号码 852+9位
         NSRange range = NSMakeRange(6,4);
         maskedNumber = [phoneNumber stringByReplacingCharactersInRange:range withString:@"****"];
     }
     return maskedNumber;
}

#pragma mark - 获取今天的前三天和后三天
- (NSArray<NSArray<NSString *> *> *)getDatesAndWeekdays {
    NSMutableArray<NSArray<NSString *> *> *datesAndWeekdays = [NSMutableArray array];
    // 获取当前日期
    NSDate *today = [NSDate date];
    // 初始化日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 日期格式化器，用于显示日期和星期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"d"];
    NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
    [dayFormatter setDateFormat:@"EEE"];
    dayFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    
    // 英文星期几到日文星期几的映射
    NSDictionary *weekdayMapping = @{
        @"Mon": @"月",
        @"Tue": @"火",
        @"Wed": @"水",
        @"Thu": @"木",
        @"Fri": @"金",
        @"Sat": @"土",
        @"Sun": @"日"
    };
    
    // 获取前三天和后三天的日期
    for (int i = -3; i <= 3; i++) {
        NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
        dateComponents.day = i;
        NSDate *date = [calendar dateByAddingComponents:dateComponents toDate:today options:0];
        NSString *dayString = [dateFormatter stringFromDate:date];
        NSString *weekdayString = [dayFormatter stringFromDate:date];
        
        // 映射到日语的星期几
        NSString *japaneseWeekday = weekdayMapping[weekdayString];
        
        [datesAndWeekdays addObject:@[dayString, japaneseWeekday]];
    }
    
    return [datesAndWeekdays copy];
}


#pragma mark - 生成二维码
-(CIImage *)createhnfgjQRcodedjgkgkWithUrlstring:(NSString *)urlString{
    // 1.实例化二维码滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢复滤镜的默认属性 (因为滤镜有可能保存上一次的属性)
    [filter setDefaults];
    // 3.将字符串转换成NSdata
    NSData *data  = [urlString dataUsingEncoding:NSUTF8StringEncoding];
    // 4.通过KVO设置滤镜, 传入data, 将来滤镜就知道要通过传入的数据生成二维码
    [filter setValue:data forKey:@"inputMessage"];
    [filter setValue:@"H" forKeyPath:@"inputCorrectionLevel"];
    // 5.生成二维码
    CIImage *outputImage = [filter outputImage];
    return outputImage;
}


- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

#pragma mark - 相册权限检测
-(void)isCanVisitPhotoLibrary:(void(^)(BOOL))result{
   PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
   if (status == PHAuthorizationStatusAuthorized) {
       result(YES);
       return;
   }
   if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
       result(NO);
       return ;
   }
   
   if (status == PHAuthorizationStatusNotDetermined) {
       
       [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
           // 回调是在子线程的
//           NSLog(@"%@",[NSThread currentThread]);
           dispatch_async(dispatch_get_main_queue(), ^{
               if (status != PHAuthorizationStatusAuthorized) {
//                     NSLog(@"未开启相册权限,请到设置中开启");
                     result(NO);
                     return ;
                 }
                 result(YES);
           });
 
       }];
   }
   
}


@end
